package com.m3958.logcollector.datacommons.controller;

import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.repository.support.Repositories;
import org.springframework.data.rest.core.config.RepositoryRestConfiguration;
import org.springframework.data.rest.core.mapping.ResourceMappings;
import org.springframework.data.rest.webmvc.ResourceNotFoundException;
import org.springframework.data.rest.webmvc.support.RepositoryEntityLinks;
import org.springframework.data.web.PagedResourcesAssembler;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import com.m3958.logcollector.datacommons.repository.M3958DataRepository;
import com.m3958.logcollector.datacommons.util.AllParams;
import com.m3958.logcollector.datacommons.util.KeyAndCount;
import com.m3958.logcollector.datacommons.util.RepoUtils;


@Controller
public class StatsController {

    private static final String BASE_MAPPING = "/stats/{repository}";

    protected final RepositoryEntityLinks entityLinks;

    private final PagedResourcesAssembler<Object> pagedResourcesAssembler;

    @Autowired
    private RepositoryRestConfiguration config;

    @Autowired
    private ResourceMappings resourceMappings;

    @Autowired
    private Repositories repositories;
    
    @Autowired
    public StatsController(Repositories repositories, //
            RepositoryRestConfiguration config, //
            RepositoryEntityLinks entityLinks, //
            PagedResourcesAssembler<Object> assembler) {
        this.entityLinks = entityLinks;
        this.pagedResourcesAssembler = assembler;
    }
    
    @RequestMapping(value = BASE_MAPPING, method = RequestMethod.GET)
    public ResponseEntity<List<KeyAndCount>> keyAndCount(HttpServletRequest request, @PathVariable String repository) {
        Map<String, String[]> allParams = request.getParameterMap();

        Object fq = (M3958DataRepository<?>) RepoUtils.findRepoByPath(repositories, resourceMappings, repository);

        if (fq == null || !(fq instanceof M3958DataRepository)) {
            throw new ResourceNotFoundException();
        }

        return ResponseEntity.ok(((M3958DataRepository<?>) fq).keyAndCount(new AllParams(allParams)));
    }

}
